package main

import (
	"fmt"
	"log"
	"net/http"
	"html/template"
	"os"
	"io"
//	"database/sql"
	_ "github.com/mattn/go-sqlite3"
)

func handleRoot(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Fprint(w, `
<html>
  <head>
    <title>Index</title>
  </head>
  <body>
  <a href="/login">Login</a></br>
  <a href="/upload">Upload</a></br>
  <a href="/sqlite">Sqlite</a></br>
  </body>
</html>
	`)

	return
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == http.MethodGet {
		unixtime, token := genToken()

		argsT := map[string]string {
			"unixtime": fmt.Sprint(unixtime),
			"token": token,
		}
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, argsT)
	} else if r.Method == http.MethodPost {
		if r.PostForm["username"][0] != "abc" ||
			r.PostForm["password"][0] != "123" {
			securePrint(w, "UserName or Password error.")
		} else {
			securePrint(w, "Get-Post UserName: ", r.Form.Get("username"))
			securePrint(w, "Get-Post2 UserName: ", r.Form["username"])
			securePrint(w, "UserName: ", r.PostForm["username"])
			securePrint(w, "PassWord: ", r.PostForm["password"])
			securePrint(w, "InputArea: ", r.PostForm["inputarea"])
			if r.PostForm.Get("remember") == "1" {
				securePrint(w, "Remember me.")
			} else {
				securePrint(w, "Do not remember me.")
			}
			securePrint(w, "CheckBox: ", r.PostForm["check"])
			securePrint(w, "UserType: ", r.PostForm["usertype"])
		}
	}

	return
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		r.ParseForm()
		_, token := genToken()
		argsT := map[string]string {
			"token": token,
		}
		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, argsT)
	} else if r.Method == http.MethodPost {
		r.ParseMultipartForm(65536)
		file, fhandler, err := r.FormFile("uploadfile")
		if err != nil {
			log.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", fhandler.Header)
		f, err := os.OpenFile("./"+fhandler.Filename, os.O_WRONLY|os.O_CREATE, 0644)
		if err != nil {
			log.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}

	return
}

func handleSqlite(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		r.ParseForm()
		t, _ := template.ParseFiles("sqlite.gtpl")
		t.Execute(w, nil)
	} else if r.Method == http.MethodPost {
		r.ParseForm()
		stmt, err := db.Prepare("INSERT INTO users(username, password) values(?, ?)")
		if err != nil {
			printEmptyHeader(w, "Prepare for sql query error.")
			defer printEmptyFooter(w)
			securePrint(w, err)
			return
		}
		res, err := stmt.Exec(r.PostForm.Get("username"),
			r.PostForm.Get("password"))
		if err != nil {
			printEmptyHeader(w, "Insert data to sql failed.")
			defer printEmptyFooter(w)
			securePrint(w, err)
			return
		}
		id, err := res.LastInsertId()
		if err != nil {
			printEmptyHeader(w, "Get last insert status error.")
			defer printEmptyFooter(w)
			securePrint(w, err)
			return
		}
		printEmptyHeader(w, "Succeed.")
		defer printEmptyFooter(w)
		securePrint(w, "Sign in succeed. Your uid is ", id)
	}

	return
}

